//产品兑换列表
let addRuleType;//添加规则的类型
let courseProductInfo={productIndex:'',courseIndex:''};//高端班按价格兑换课程添加规则列表选中索引（因为两个列表宽度不够，当固定列时会出现相同id的列表，直接取不到对应选中数据）
let selectCourseIndex='';//现场参会、行业交流、高端班兑换天数添加规则时选中的兑换课程索引
let productData=[],courseData=[];//存储添加规则弹出页面对应产品列表和课程列表数据
let $exchangeDetailsTable=$("#exchangeDetailsTable");
let examineFilePath;
//防止表头与表格不对齐
$(window).resize(function () {
    $("#dayExchange").bootstrapTable('resetView');
    $("#communicationExchange").bootstrapTable('resetView');
    $("#priceExchange").bootstrapTable('resetView');
    $("#courseExchangeDays").bootstrapTable('resetView');
    $("#daysExchangeCommunication").bootstrapTable('resetView');
    $("#communicationExchangeDays").bootstrapTable('resetView');

    $("#exchangeCourse").bootstrapTable('resetView');
    $("#productList").bootstrapTable('resetView');
    $("#courseList").bootstrapTable('resetView');

    $exchangeDetailsTable.bootstrapTable('resetView');
});

$(function () {
    //兑换明细列表
    exchangeDetailsList()
    $('.datepicker').datepicker({
        language: "zh-CN",
        autoclose: true, //选择后自动关闭
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#arriveTimeStart').on('changeDate',function(){
        var startDate = $('#arriveTimeStart').val();
        var endDate = $('#arriveTimeEnd').val();
        if (endDate < startDate) {  // 对比结束日期和新的起止日期，起止日期大于结束日期则清空结束日期
            $('#arriveTimeEnd').val('');
        }
        $('#arriveTimeEnd').datepicker('destroy').datepicker({
            language: "zh-CN",
            autoclose: true, //选择后自动关闭
            clearBtn: true,
            todayHighlight: true,
            format: "yyyy-mm-dd",
            startDate: new Date(startDate)
        });
    });
})
//加载列表
function productExchangeList(domId,url,thName,thValue) {
    let exchangeName = arguments[4]?arguments[4]:'兑换课程名称';
    let exchangeValue = arguments[5]?arguments[5]:'changeCourseTitle';
    $(`#${domId}`).bootstrapTable('destroy');//先销毁表格
    $(`#${domId}`).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url:url,//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        height:400,
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [20, 50],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: queryParams,//查询参数
        columns: [
            {title: '规则编号', field: 'ruleNumber', align: 'left', valign: 'middle',width: '140'},
            {title: '规则标题', field: 'ruleTitle', align: 'left', valign: 'middle'},
            {title: thName, field: thValue, align: 'left', valign: 'middle',width: arguments[4]?'':'100'},
            {title: exchangeName, field: exchangeValue, align: 'left', valign: 'middle',width: arguments[4]?'100':''},
            {title: '创建日期', field: 'createTm', align: 'left', valign: 'middle', width: '140'},
            {title: '操作', field: 'operate', align: 'right', width: '120',events: operateEvents,formatter:genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //table列可拖动宽度
            $('.JCLRgrips').remove();
            $(`#${domId}`).css({
                minWidth: $(`#${domId}`).width()
            })
        },

        // onLoadSuccess: function () {
        //     $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        // },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

//添加规则--查询列表
function exchangeCourseList(domId,url,thName,productCategories,productName) {
    if(url.indexOf('selectHighCustomerMemberProductList')==-1){
        var productCode='productCode';
        var productNames='productName';
    }else{
        var productCode='memberProductCode';
        var productNames='memberCardName';
    }
    $(`#${domId}`).bootstrapTable('destroy');//先销毁表格
    $(`#${domId}`).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url:url,//请求地址
        // height:280,
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'companyId',
        idField: 'companyId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [5, 10, 15, 20],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedRightNumber: domId=='exchangeCourse'?0:1,    // 右侧固定列
        queryParams:function(params){
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;
            params.sortName = params.sort; //排序列名
            params.sortOrder = params.order;//排序方式
            //搜索条件
            if(url.indexOf('selectHighCustomerMemberProductList')==-1){
                params.productCategories = productCategories;
                params.productName = productName;
            }else{
                params.productName = productName;
            }
            return params;

        },//查询参数
        columns: [
            // {checkbox: true, visible: true},
            {title: '产品编号', field: productCode, align: 'left', valign: 'middle',width: '140'},
            {title: thName, field: productNames, align: 'left',valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right', width: '100',formatter:function(value, row, index) {
                 let html = `<div class="form-check">
                  <label class="form-check-label">
                    <input style="vertical-align: middle;margin-right:5px!important" class="form-check-input" onchange="checkedChange(this)" type="checkbox">勾选
                  </label>
                </div>`;
                    return html;
                }}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                if(domId==='courseList'){
                    courseData=result.data;
                }else{
                    productData=result.data;
                }
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
                if(domId==='courseList'){
                    courseData=[];
                }else{
                    productData=[];
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // //table列可拖动宽度
            // $('.JCLRgrips').remove();
            // $(`#${domId}`).css({
            //     minWidth: $(`#${domId}`).width()
            // })
        },

        // onLoadSuccess: function () {
        //     $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        // },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    //当前状况：1启用  2 停用
    let html =  `<button type="button" class="btn-default activeBtn" id="deactivate">${row.enableDisable==1?"停用":"启用"}</button>`;
    return html;
}
window.operateEvents = {
    //点击事件
    'click #deactivate': function (e, value, row, index) {
        $.confirm({
            title: '提示',
            content: `是否确认${row.enableDisable==1?"停用":"启用"}`,
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function () {
                        updateEnableDisable(row)
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'btn-primary',
                    action: function () {
                        return;
                    }
                }
            }
        });


    },
    'click #details': function (e, value, row, index){
        getExchangeDetail(row.changeCourseId);
        $("#exchangeDetailModal").modal('show');

    }
};
let fileObj={
    "xcch": "现场参会剩余次数",
    "hyhsycs": "行业会剩余次数",
    "memberCardNumber": "会员卡号",
    "ruleNumber": "规则编码",
    "createTm": "创建时间",
    "updateTm": "更新时间",
    "finishOrderProductNum": "兑换完的产品号",
    "finishProductName": "兑换完的产品名称",
    "examine": "审核状态",
    "uploadId": "相关附件",
    "changeCourseType": "兑换方式",
    "gdbChangeXcch": "高端班兑换的现场天数",
    "approverId": "审批人",
    'productType':'支付类型',
    "remarks": "备注",
};
function getExchangeDetail(changeCourseId){
    $.ajax({
        url: '/csd/productManager/selectViewDetails',
        type: 'POST',
        dataType: "json",
        data: {
            changeCourseId:changeCourseId,
        },
        success: (function (data) {
            if (data.code == '000000') {
                getHtml('exchangeDtails',data.data,fileObj)
            }
        }),
        error: (function () {
            $.alert("请求失败");
        })
    })

}
function getHtml(parentId,dataObj,fileObj){
    examineFilePath = dataObj.uploadId;
    let html='';
    for(var key in fileObj){
        var label=fileObj[key],value='';
        var str1=``;
        if(key=='uploadId'){
            str1 = ` <a href="javascript:;" style="line-height:36px;margin-left:5px;" onclick="showFile(1);">查看</a>`
        }else{
            //值的判断
            if(key=='productType'){
                switch(dataObj[key]){
                    case '1':
                        value='线上支付';
                        break;
                    case '2':
                        value='线下支付';
                        break;
                }
            }
            else if(key=='changeCourseType'){
                switch(dataObj[key]){
                    case '0':
                        value='现场天数兑换课程';
                        break;
                    case '1':
                        value='专行业交流次数兑换课程';
                        break;
                    case '2':
                        value='高端班兑换课程';
                        break;
                    case '3':
                        value='高端班兑换现场天数';
                        break;
                    case '4':
                        value='现场天数兑换行业会';
                        break;
                    case '5':
                        value='行业会兑换现场天数';
                        break;

                }

            }
            else if(key=='examine'){
                switch(dataObj[key]){
                    case '0':
                        value='通过';
                        break;
                    case '1':
                        value='待审批';
                        break;
                    case '2':
                        value='不通过';
                        break;

                }

            }else{
                value=(!dataObj[key] && typeof(dataObj[key])!="undefined" && dataObj[key]!=0)?'':dataObj[key];
            }
            //格式判断
            if(key=='remarks'){
                str1= `<textarea class="form-control" readonly id="remarks" rows="3" style="width:calc(100% + 25px);resize: none">${value}</textarea>`;
            }else{
                str1= `<span style="line-height: 35px;font-weight:bold;margin-left:5px;">${value}</span>`;
            }
        }
        var str0=key=='remarks'?`col-lg-12 col-md-12 col-sm-12`:`col-lg-6 col-md-6 col-sm-6`;
        var str=`<div class="form-group clearFix`+str0+`col-xs-12">
                            <label class="control-label pull-left">${label}:</label>
                            <div class="form-content">`+str1+`                               
                            </div>
                        </div>`;
        html+=str;
    }
    $(`#${parentId}`).html(html)

}
function updateEnableDisable(row){
    let id;
    switch(row.type){
        case 1:
            id = row.sceneCourseId;
            break;
        case 2:
            id = row.industryCourseId;
            break;
        case 3:
            id = row.highClassCourseId;
            break;
        case 4:
            id = row.highClassExchangeFateId;
            break;
        case 5:
            id = row.siteExchangeIndustryId;
            break;
        case 6:
            id = row.industryExchangeSiteId;
            break;
    }
    let params = {
        id:id,
        enableDisable:row.enableDisable==1?'2':'1',
        type:row.type
    };
    $.ajax({
        url: '/csd/ProductExchange/updateEnableDisable',
        type: 'POST',
        dataType: 'json',
        data: params,
        success:function(data) {
            if(data.code=='000000'){
                $.alert(`${row.enableDisable==1?"停用":"启用"}成功`);
                switch(row.type){
                    case 1:
                        productExchangeList('dayExchange','/csd/ProductExchange/selectProductSceneList','现场参会天数','sceneParameterDays')
                        break;
                    case 2:
                        productExchangeList('communicationExchange','/csd/ProductExchange/selectProductIndustryList','行业会交流次数','industryExchangeNumber')
                        break;
                    case 3:
                        productExchangeList('priceExchange','/csd/ProductExchange/selectProductHighClassList','产品名称','productName')
                        break;
                    case 4:
                        productExchangeList('courseExchangeDays','/csd/ProductExchange/selectHighClassExchangeDaysList','课程名称','productName','兑换天数','exchangeDays')
                        break;
                    case 5:
                        productExchangeList('daysExchangeCommunication','/csd/ProductExchange/selectSiteExchangeIndustryList','现场天数','siteDays','行业会次数','industryNumber')
                        break;
                    case 6:
                        productExchangeList('communicationExchangeDays','/csd/ProductExchange/selectIndustryExchangeSiteList','行业会次数','industryNumber','现场天数','siteDays')
                        break;
                }

            }else{
                $.alert(data.message)
            }
        },
        error:function() {
            $.alert('请求失败')
        }
    })
}

function checkedChange(dom){
    let tableId=$(dom).parents("table").attr("id");
    if($(dom).is("input:checked")){
        if(tableId==='productList'){
            courseProductInfo['productIndex']=$(dom).parents("tr").index()
        }else if(tableId==='courseList'){
            courseProductInfo['courseIndex']=$(dom).parents("tr").index()
        }else{
            //现场参会、行业交流、高端班兑换天数选择的兑换课程索引
            selectCourseIndex=$(dom).parents("tr").index()
        }
        $(dom).parents("tr").siblings("tr").find("input").attr({"checked":false})
    }else{
        if(tableId==='productList'){
            courseProductInfo['productIndex']='';
        }else if(tableId==='courseList'){
            courseProductInfo['courseIndex']='';
        }else{
            //现场参会、行业交流、高端班兑换天数选择的兑换课程索引
            selectCourseIndex=''
        }
    }

}
function changeTab(productCategory){
    if(productCategory=='rule'){
        //兑换规则设置 列表初始化
        productExchangeList('dayExchange','/csd/ProductExchange/selectProductSceneList','现场参会天数','sceneParameterDays')
        productExchangeList('communicationExchange','/csd/ProductExchange/selectProductIndustryList','行业会交流次数','industryExchangeNumber')
        productExchangeList('priceExchange','/csd/ProductExchange/selectProductHighClassList','产品名称','productName')
        productExchangeList('courseExchangeDays','/csd/ProductExchange/selectHighClassExchangeDaysList','课程名称','productName','兑换天数','exchangeDays')
        productExchangeList('daysExchangeCommunication','/csd/ProductExchange/selectSiteExchangeIndustryList','现场天数','siteDays','行业会次数','industryNumber')
        productExchangeList('communicationExchangeDays','/csd/ProductExchange/selectIndustryExchangeSiteList','行业会次数','industryNumber','现场天数','siteDays')
    }
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    return params;
}

function productNameSearch(self,domId,thName,type){
    if(domId==='productList'){
        courseProductInfo['productIndex']='';
    }else if(domId==='courseList'){
        courseProductInfo['courseIndex']='';
    }else{
        //现场参会、行业交流、高端班兑换天数 选择的兑换课程索引
        selectCourseIndex=''
    }
    let productName = $.trim($(self).siblings("input").val());
    if(addRuleType=='days'||addRuleType=='communications'){
        exchangeCourseList(domId,'/csd/ProductExchange/selectProductList',thName,'0',productName);
    }else if(addRuleType=='courseExchangeDays'){
        //课程兑换天数
        exchangeCourseList('exchangeCourse','/csd/ProductExchange/selectHighCustomerMemberProductList','产品名称','',productName)
    }else if(addRuleType=='product'){
        //高端班兑换课程
        if(domId==='productList'){
            exchangeCourseList('productList','/csd/ProductExchange/selectHighCustomerMemberProductList','产品名称','',productName)
        }else if(domId==='courseList'){
            exchangeCourseList('courseList','/csd/ProductExchange/selectProductList',thName,'0',productName);
        }
    }

}
//添加规则
function addRule(exchangeType){
    addRuleType = exchangeType;
    $("#addRuleModal").find("input").val("");//输入框为空
    $("#addRuleModal").find("input:checked").attr({"checked":false});
    $("#addRuleModal").modal('show');
    setTimeout(function(){
        if(exchangeType==='product'){
            productModal();
            courseProductInfo={productIndex:'',courseIndex:''};
            exchangeCourseList('productList','/csd/ProductExchange/selectHighCustomerMemberProductList','产品名称','','')
            exchangeCourseList('courseList','/csd/ProductExchange/selectProductList','产品名称','0','')
            //清除校验
            $('#highExchangeCourseForm').data('bootstrapValidator')?$('#highExchangeCourseForm').data('bootstrapValidator').destroy():'';//清除校验
            //表单校验
            formValidator0()
        }else{
            if(exchangeType=='daysExchangeCommunication'){
                dayCommunicationModal()
                //清除校验
                $('#exchangeCommunicationNumber').data('bootstrapValidator')?$('#exchangeCommunicationNumber').data('bootstrapValidator').destroy():'';//清除校验
                //表单校验
                formValidator1()

            }else if(exchangeType=='communicationExchangeDays'){
                communicationDayModal()
                //清除校验
                $('#exchangeDayNumber').data('bootstrapValidator')?$('#exchangeDayNumber').data('bootstrapValidator').destroy():'';//清除校验
                //表单校验
                formValidator2()

            }else{
                //现场参会、行业交流、高端班兑换天数
                if(exchangeType=='courseExchangeDays'){
                    $("#exchangeName").text("兑换天数:");
                    //兑换课程列表 会员
                    exchangeCourseList('exchangeCourse','/csd/ProductExchange/selectHighCustomerMemberProductList','课程名称','','')
                }else{
                    $("#exchangeName").text("兑换次数:")
                    //兑换课程列表 非会员
                    exchangeCourseList('exchangeCourse','/csd/ProductExchange/selectProductList','课程名称','0','')
                };
                //现场参会、行业交流、高端班兑换天数选择的兑换课程索引
                selectCourseIndex='';
                numberModal();
                //清除校验
                $('#exchangeNumber').data('bootstrapValidator')?$('#exchangeNumber').data('bootstrapValidator').destroy():'';//清除校验
                //表单校验
                formValidator()
            }


        }
    },100)


}
function numberModal(){
    $("#addRuleModal .modal-dialog").css({"width":'720px'});
    $("#btnsContainer").css({"justify-content":'flex-end'});
    $("#numberExchangeRule").show();
    $("#productExchangeRule").hide();
    $("#dayCommunicationExchangeRule").hide();
    $("#communicationDayExchangeRule").hide();
}
//高端班兑换课程
function productModal(){
    $("#addRuleModal .modal-dialog").css({"width":'920px'});
    $("#btnsContainer").css({"justify-content":'center'});
    $("#productExchangeRule").show();
    $("#numberExchangeRule").hide();
    $("#dayCommunicationExchangeRule").hide();
    $("#communicationDayExchangeRule").hide();
}
//现场天数兑换行业会次数
function dayCommunicationModal(){
    $("#addRuleModal .modal-dialog").css({"width":'450px'});
    $("#btnsContainer").css({"justify-content":'flex-end'});
    $("#dayCommunicationExchangeRule").show();
    $("#numberExchangeRule").hide();
    $("#productExchangeRule").hide();
    $("#communicationDayExchangeRule").hide();

}
//行业会次数兑换现场天数
function communicationDayModal(){
    $("#addRuleModal .modal-dialog").css({"width":'450px'});
    $("#btnsContainer").css({"justify-content":'flex-end'});
    $("#communicationDayExchangeRule").show();
    $("#numberExchangeRule").hide();
    $("#productExchangeRule").hide();
    $("#dayCommunicationExchangeRule").hide();

}

//关闭添加规则页面
function closeRule(){
    $("#addRuleModal").modal('hide');
}
//表单校验
function formValidator(){
    let tipName = addRuleType == 'courseExchangeDays'?'兑换天数':'兑换次数';
    $('#exchangeNumber').bootstrapValidator({
        fields: {
            commonRuleTitle: {
                validators: {
                    notEmpty: {
                        message: `规则标题不能为空`
                    }
                }
            },
            changeNumber: {
                validators: {
                    notEmpty: {
                        message: `${tipName}不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `${tipName}为正整数`
                    }

                }
            },
            dayNumber: {
                validators: {
                    notEmpty: {
                        message: `现场天数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `现场天数为正整数`
                    }

                }
            },
            changeCommunicationNumber: {
                validators: {
                    notEmpty: {
                        message: `兑换次数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `兑换次数为正整数`
                    }

                }
            },
            communicationNumber: {
                validators: {
                    notEmpty: {
                        message: `行业会次数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `行业会次数为正整数`
                    }

                }
            },
            changeDayNumber:{
                validators: {
                    notEmpty: {
                        message: `兑换天数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `兑换天数为正整数`
                    }

                }

            }
        }
    });
}
//表单校验 <!--高端班兑换课程-->
function formValidator0(){
    $('#highExchangeCourseForm').bootstrapValidator({
        fields: {
            highExchangeCourseRuleTitle: {
                validators: {
                    notEmpty: {
                        message: `规则标题不能为空`
                    }
                }
            }
        }
    });
}
//表单校验 <!--现场天数兑换行业会次数-->
function formValidator1(){
    $('#exchangeCommunicationNumber').bootstrapValidator({
        fields: {
            dayRuleTitle: {
                validators: {
                    notEmpty: {
                        message: `规则标题不能为空`
                    }
                }
            },
            dayNumber: {
                validators: {
                    notEmpty: {
                        message: `现场天数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `现场天数为正整数`
                    }

                }
            },
            changeCommunicationNumber: {
                validators: {
                    notEmpty: {
                        message: `兑换次数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `兑换次数为正整数`
                    }

                }
            },
            communicationNumber: {
                validators: {
                    notEmpty: {
                        message: `行业会次数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `行业会次数为正整数`
                    }

                }
            },
            changeDayNumber:{
                validators: {
                    notEmpty: {
                        message: `兑换天数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `兑换天数为正整数`
                    }

                }

            }
        }
    });
}
//表单校验 <!--行业会次数兑换现场天数-->
function formValidator2(){
    $('#exchangeDayNumber').bootstrapValidator({
        fields: {
            communicationRuleTitle: {
                validators: {
                    notEmpty: {
                        message: `规则标题不能为空`
                    }
                }
            },
            communicationNumber: {
                validators: {
                    notEmpty: {
                        message: `行业会次数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `行业会次数为正整数`
                    }

                }
            },
            changeDayNumber:{
                validators: {
                    notEmpty: {
                        message: `兑换天数不能为空`
                    },
                    regexp: {
                        regexp: /(^[1-9]\d*$)/,
                        message: `兑换天数为正整数`
                    }

                }

            }
        }
    });
}
function reset(){
    $("#addRuleModal").find("input").val("");//输入框为空
    $("#addRuleModal").find("input:checked").attr({"checked":false});
    if(addRuleType==='product'){
        courseProductInfo={productIndex:'',courseIndex:''};
        exchangeCourseList('productList','/csd/ProductExchange/selectHighCustomerMemberProductList','产品名称','','')
        exchangeCourseList('courseList','/csd/ProductExchange/selectProductList','产品名称','0','')
        //清除校验
        $('#highExchangeCourseForm').data('bootstrapValidator')?$('#highExchangeCourseForm').data('bootstrapValidator').destroy():'';//清除校验
        //表单校验
        formValidator0()
    }else if(addRuleType==='daysExchangeCommunication'){
        //清除校验
        $('#exchangeCommunicationNumber').data('bootstrapValidator')?$('#exchangeCommunicationNumber').data('bootstrapValidator').destroy():'';//清除校验
        //表单校验
        formValidator1()

    }else if(addRuleType==='communicationExchangeDays'){
        //清除校验
        $('#exchangeDayNumber').data('bootstrapValidator')?$('#exchangeDayNumber').data('bootstrapValidator').destroy():'';//清除校验
        //表单校验
        formValidator2()

    }else{
        //现场参会、行业交流、高端班兑换天数选择的兑换课程索引
        selectCourseIndex='';
        //清除校验
        $('#exchangeNumber').data('bootstrapValidator')?$('#exchangeNumber').data('bootstrapValidator').destroy():'';//清除校验
        //表单校验
        formValidator()
        //兑换课程列表
        if(addRuleType==='courseExchangeDays'){
            //高端班兑换天数
            exchangeCourseList('exchangeCourse','/csd/ProductExchange/selectHighCustomerMemberProductList','产品名称','','')
        }else{
            //现场参会、行业交流
            exchangeCourseList('exchangeCourse','/csd/ProductExchange/selectProductList','产品名称','0','')

        }
    }
}
function submitRule(){
    let url='';
    let params={};
    if(addRuleType!=='product'){
        let formDom=$('#exchangeNumber');
        if(addRuleType=="daysExchangeCommunication"){
            formDom=$('#exchangeCommunicationNumber');
        }else if(addRuleType=="communicationExchangeDays"){
            formDom=$('#exchangeDayNumber');
        }
        var bootstrapValidator = formDom.data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }
        if(addRuleType=="daysExchangeCommunication"){
            url='/csd/ProductExchange/addSiteExchangeIndustry';
            params={
                'ruleTitle':$.trim($("#dayRuleTitle").val()),
                'siteDays':$("#dayNumber").val(),
                'industryNumber':$("#changeCommunicationNumber").val()
            }

        }else if(addRuleType=="communicationExchangeDays"){
            url='/csd/ProductExchange/addIndustryExchangeSite';
            params={
                'ruleTitle':$.trim($("#communicationRuleTitle").val()),
                'industryNumber':$("#communicationNumber").val(),
                'siteDays':$("#changeDayNumber").val()
            }

        }else{
           /* let selectCourse=$("#exchangeCourse").find("input:checked");*/
            if(typeof(selectCourseIndex)!='number'){
                $.alert("请选择兑换课程");
                return;
            }else{
                /*let selectIndex=selectCourse.parents("tr").index();*/
                if(addRuleType==='days'){
                    url='/csd/ProductExchange/addProductScene';
                    params={
                        'ruleTitle':$.trim($("#commonRuleTitle").val()),
                        'sceneParameterDays':$.trim($("#changeNumber").val()),
                        'changeCourseTitle':productData[selectCourseIndex]['productName'],
                        'courseProductCode':productData[selectCourseIndex]['productCode'],
                        'productType':productData[selectCourseIndex]['productType'],
                        'customerProductId':productData[selectCourseIndex]['customerProductId']
                    }
                } else if(addRuleType==='communications'){
                    url='/csd/ProductExchange/addProductIndustry';
                    params={
                        'ruleTitle':$.trim($("#commonRuleTitle").val()),
                        'industryExchangeNumber':$("#changeNumber").val(),
                        // 'changeCourseTitle':selectCourse.parents("tr").find("td:nth-of-type(2)").text(),
                        // 'courseProductCode':selectCourse.parents("tr").find("td:nth-of-type(1)").text()
                        'changeCourseTitle':productData[selectCourseIndex]['productName'],
                        'courseProductCode':productData[selectCourseIndex]['productCode'],
                        'productType':productData[selectCourseIndex]['productType'],
                        'finishOrderProductNum':productData[selectCourseIndex]['finishOrderProductNum']
                    }

                }else if(addRuleType==='courseExchangeDays'){
                    url='/csd/ProductExchange/addHighClassExchangeDays';
                    params={
                        'ruleTitle':$.trim($("#commonRuleTitle").val()),
                        'exchangeDays':$("#changeNumber").val(),
                        'productName':productData[selectCourseIndex]['memberCardName'],
                        'productCode':productData[selectCourseIndex]['memberProductCode'],
                        'memberProductId':productData[selectCourseIndex]['memberProductId']
                    }

                }
            }
        }



    }else{
        var bootstrapValidator = $("#highExchangeCourseForm").data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }
        url='/csd/ProductExchange/addProductHighClass';
        if(courseProductInfo.productIndex===''){
            $.alert("请选择产品");
            return;
        };
        if(courseProductInfo.courseIndex===''){
            $.alert("请选择兑换课程");
            return;
        };
        params={
            // 'productName':$("#productList tbody").find("tr").eq(courseProductInfo.productIndex).find("td:nth-of-type(2)").text(),
            // 'changeCourseTitle':$("#courseList tbody").find("tr").eq(courseProductInfo.courseIndex).find("td:nth-of-type(2)").text(),
            // 'productCode':$("#productList tbody").find("tr").eq(courseProductInfo.productIndex).find("td:nth-of-type(1)").text(),
            // 'courseProductCode':$("#courseList tbody").find("tr").eq(courseProductInfo.courseIndex).find("td:nth-of-type(1)").text(),
            'ruleTitle':$.trim($("#highExchangeCourseRuleTitle").val()),
            'productName':productData[courseProductInfo.productIndex]['memberCardName'],
            'changeCourseTitle':courseData[courseProductInfo.courseIndex]['productName'],
            'productCode':productData[courseProductInfo.productIndex]['memberProductCode'],
            'courseProductCode':courseData[courseProductInfo.courseIndex]['productCode'],
            'productType':courseData[courseProductInfo.courseIndex]['productType'],
            'memberProductId':courseData[courseProductInfo.courseIndex]['memberProductId'],
            'courseOriginalPrice':courseData[courseProductInfo.courseIndex]['courseOriginalPrice']
        }

    }
    $.ajax({
        type: "post",
        url: url,
        dataType: 'json',
        data:params,
        success: function (data) {
            if(data.code==='000000'){
                if(addRuleType==='days'){
                    productExchangeList('dayExchange','/csd/ProductExchange/selectProductSceneList','现场参会天数','sceneParameterDays')
                }else if(addRuleType==='communications'){
                    productExchangeList('communicationExchange','/csd/ProductExchange/selectProductIndustryList','行业会交流次数','industryExchangeNumber')
                }else if(addRuleType==='product'){
                    productExchangeList('priceExchange','/csd/ProductExchange/selectProductHighClassList','产品名称','productName')
                }else if(addRuleType==='courseExchangeDays'){
                    productExchangeList('courseExchangeDays','/csd/ProductExchange/selectHighClassExchangeDaysList','课程名称','productName','兑换天数','exchangeDays')
                }else if(addRuleType==='daysExchangeCommunication'){
                    productExchangeList('daysExchangeCommunication','/csd/ProductExchange/selectSiteExchangeIndustryList','现场天数','siteDays','行业会次数','industryNumber')
                }else if(addRuleType==='communicationExchangeDays'){
                    productExchangeList('communicationExchangeDays','/csd/ProductExchange/selectIndustryExchangeSiteList','行业会次数','industryNumber','现场天数','siteDays')
                }
                $.alert('保存成功');
                closeRule();

            }else{
                $.alert(data.message)
            }

        },
        error: function (error) {
            $.alert(error.message)
        }
    });
}
//兑换明细页面下的方法
//兑换明细列表
function exchangeDetailsList() {
    closeFilterContainer();//关闭高级筛选
    $exchangeDetailsTable.bootstrapTable('destroy');//先销毁表格
    $exchangeDetailsTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/csd/ProductExchange/selectChangeCourseRecord',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        height:820,
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [20, 50],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: exchangeDetailParams,//查询参数
        columns: [
            {title: '兑换前产品', field: 'finishProductName', align: 'left', valign: 'middle'},
            {title: '兑换后产品', field: 'changeCourseTitle', align: 'left', valign: 'middle'},
            {title: '所属订单', field: 'orderNumber', align: 'left', valign: 'middle',width: '120'},
            {title: '所属合同', field: 'contractNumber', align: 'left', valign: 'middle',width: '120'},
            {title: '兑换规则标题', field: 'ruleTitle', align: 'left', valign: 'middle',width: '120'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '所属人', field: 'userName', align: 'left', valign: 'middle', width: '100'},
            {title: '兑换时间', field: 'createTm', align: 'left', valign: 'middle', width: '100'},
            {title: '操作', field: 'operate', align: 'right',events: operateEvents,formatter:exchangeDetailgenderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#customerTableList').css({
                minWidth: $('#customerTableList').width()
            })
        },

        // onLoadSuccess: function () {
        //     $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        // },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}
//兑换明细参数
function exchangeDetailParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    // params.dateType = $("#dateType").val();//全部
    params.startDate = $.trim($('#arriveTimeStart').val());//开始日期
    params.endDate= $.trim($('#arriveTimeEnd').val());//截止日期
    params.ruleTitle = $("#ruleTitle").val()
    return params;
}
/**
 * 自定义操作列内容
 */
function exchangeDetailgenderOpt(value, row, index) {
    let html = '<button type="button" class="btn-default activeBtn detailBtn" id="details">查看明细</button>';
    return html;
}
/**
 * 全部/今天/周/月/上月/自定义切换
 * @param time
 */
function selectTime(time) {
    $('.timeBtn').removeClass('active-second');
    $(`#${time}`).addClass('active-second');
    if(time==='customize'){
        //自定义
        $("#dateType").val("");
        if($('#customInput').is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }
    }else{
        //全部
        $('#customInput').hide();
        $('#arriveTimeStart').val('');
        $('#arriveTimeEnd').val('');
        $("#dateType").val("");
        exchangeDetailsList();
    }

}
//打开高级筛选弹框
function openFilterContainer(){
    $("#closeFilter").show();
    $("#openFilter").hide();
    $("#filterFilesContainer").slideDown();
}
//关闭高级筛选弹框
function closeFilterContainer(){
    $("#openFilter").show();
    $("#closeFilter").hide();
    $("#filterFilesContainer").slideUp();
}
//点击高级筛选切换显示隐藏
function showToggle(){
    if($("#filterFilesContainer").is(":hidden")){
        openFilterContainer()
    }else{
        closeFilterContainer()
    }
}